<script setup lang="ts">
import { ref } from 'vue';
import { CloudArrowUpIcon } from '@heroicons/vue/24/outline';
import { usePhotoStore } from '../stores/photoStore';

const emit = defineEmits<{
  (e: 'upload', files: File[]): void
}>();

const photoStore = usePhotoStore();
const dragActive = ref(false);
const fileInput = ref<HTMLInputElement | null>(null);
const uploading = ref(false);

const handleDrag = (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  if (e.type === "dragenter" || e.type === "dragover") {
    dragActive.value = true;
  } else if (e.type === "dragleave") {
    dragActive.value = false;
  }
};

const handleDrop = async (e: DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  dragActive.value = false;
  if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
    await handleFiles(Array.from(e.dataTransfer.files));
  }
};

const handleChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    await handleFiles(Array.from(target.files));
  }
};

const handleFiles = async (files: File[]) => {
  uploading.value = true;
  try {
    for (const file of files) {
      await photoStore.addPhoto(file, file.name.replace(/\.[^/.]+$/, ""), `上传于 ${new Date().toLocaleDateString()}`);
    }
    emit('upload', files);
  } catch (error) {
    console.error('Upload failed:', error);
  } finally {
    uploading.value = false;
  }
};

const openFileDialog = () => {
  fileInput.value?.click();
};
</script>

<template>
  <div
    @dragenter="handleDrag"
    @dragover="handleDrag"
    @dragleave="handleDrag"
    @drop="handleDrop"
    class="upload-zone"
    :class="{ 'drag-active': dragActive }"
  >
    <input
      ref="fileInput"
      type="file"
      multiple
      accept="image/*"
      class="hidden"
      @change="handleChange"
    />
    
    <div class="upload-content" @click="openFileDialog">
      <CloudArrowUpIcon class="w-12 h-12 text-white/50" />
      <h3 class="mt-4 text-xl font-semibold text-white">上传照片</h3>
      <p class="mt-2 text-sm text-gray-400">
        拖放照片到这里，或点击选择文件
      </p>
      <p class="mt-1 text-xs text-gray-500">
        支持格式：JPG、PNG、WebP
      </p>
      <div v-if="uploading" class="mt-4">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-white mx-auto"></div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.upload-zone {
  width: 100%;
  min-height: 300px;
  border: 2px dashed rgba(255, 255, 255, 0.2);
  border-radius: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover, &.drag-active {
    border-color: rgba(255, 255, 255, 0.5);
    background: rgba(255, 255, 255, 0.05);
  }
}

.upload-content {
  text-align: center;
  padding: 2rem;
}
</style>